package com.baozun.test;

import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

public class FTPUtil {
    private int port = 22;
    private String baozunurl = "hub.baozun.cn";
    private String testurl = "10.11.21.11";


    private String[] usernameArray = new String[] {"aeotmall201312", "anftmall201406", "ck140731", "coachec", "coachec2", "boc_follif201307", "godiva201210", "gopro0915", "guess201307", "jbb201405", "mas", "mas_test", "natualcare201406", "nike-prd",
            "nikedoms201311", "nilewh201404", "niledbox201404", "Nike-GB2-Test", "omsrefund20141014", "ua201210", "boc-wmf201307", "wms201409", "yxdr0904", "novo20141202", "bizhubread88", "cathk20141216", "ppg20141216", "ANF", "appletmall201312",
            "boc-sina201312", "coach02", "crm201402", "esprit", "esprittest", "esp_rpt", "etam201206", "ids-prd2012", "Kerry-ck201307", "lf-ids0821", "microsoft201210", "microsoft20140714", "next140812", "nikehk201406", "nikehktest201406", "nike_store",
            "niketest", "niletmall201401", "sephora0819", "levisecom01"};
    private String[] passwordArray = new String[] {"zX3sia9bYwfE", "mdVNBybsWkNY", "ck@hub%if731", "c0@ch432e", "coachec2@#123!", "qzZfu1KOAiy5", "uytGBNm98", "gopro9^53dj", "Ia8KPCa8VLro", "GyjAM2nkwjy1", "mas2012A!", "mNs_bZt1sT", "Ub2llyZyg2SC",
            "zxcvf%$#2w", "t5khkT5rsdvB", "JBPheFT92ze8", "fngQ9X5T7Lq8", "nike123!@#test", "!omsRefund%123", "ygvbNJIaw3@!", "erzyzQD5PRfR", "wms201409!@#WMS", "yxdr7^53%", "novo@#123!", "bizhub_Read#88", "cathk!88@#%1234", "ppg!88^%#1234",
            "UrTgBDIg6qxM", "rXgRz2er4sg8", "ugO1LeZ9yiEu", "c0@ch20e2", "oMoFssAofYcq", "Esprit543@!2012", "QWE!@#123asd", "ESP_rpt321", "oiujk65RTy", "Ert67pl,mn", "esBjSgbL3Mls", "lfids^sftp$1010%&", "weiRuanst12!0", "msiop123$%^", "next@hub%app812",
            "91sVHCVzFkBA", "Z7ZvYs1rdzGq", "njiuyhK2013", "niketest", "Sfgglyr0tbUB", "sephora@hub%819$", "levisecom0212"};

    public static void main(String[] args) {
        // new FTPUtil().copyFile();
        new FTPUtil().compareUsername();
    }

    public void compareUsername() {
        int index = 0;
        for (String username : usernameArray) {
            String password = passwordArray[index];
            Session sessionBaozun = null;
            ChannelSftp sftpBaozun = null;
            try {
                JSch jsch = new JSch();
                sessionBaozun = jsch.getSession(username, baozunurl, port);
                sessionBaozun.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sessionBaozun.setConfig(sshConfig);
                sessionBaozun.connect();
                Channel channel = sessionBaozun.openChannel("sftp");
                channel.connect();
                sftpBaozun = (ChannelSftp) channel;
                
            } catch (JSchException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("baozunurl:>" + baozunurl + "用户名:" + username + "无法连接！");
            }finally{
                sessionBaozun.disconnect();
                sftpBaozun.disconnect();
            }
            Session sessionTest = null;
            ChannelSftp sftpTest = null;
            try {
                JSch jsch = new JSch();
                sessionTest = jsch.getSession(username, testurl, port);
                sessionTest.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sessionTest.setConfig(sshConfig);
                sessionTest.connect();
                Channel channel = sessionTest.openChannel("sftp");
                channel.connect();
                sftpTest = (ChannelSftp) channel;
            } catch (JSchException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("testurl:>" + testurl + "用户名:" + username + "无法连接！");
            }finally{
                sessionTest.disconnect();
                sftpTest.disconnect();
            }

        }
    }

    public void copyFile() {
        int index = 0;
        for (String username : usernameArray) {
            Session sessionFrom = null;
            ChannelSftp sftpFrom = null;
            Session sessionTo = null;
            ChannelSftp sftpTo = null;
            String password = passwordArray[index];
            try {
                sftpFrom = getSftp(sessionFrom, sftpFrom, baozunurl, port, username, password);
                sftpTo = getSftp(sessionTo, sftpTo, testurl, port, username, password);
                System.out.println("用户开始比对:" + username);
                copyFile(sftpFrom, sftpTo, "/home/" + username, "/home/SFTP/" + username);
                System.out.println("该用户比对结束");
            } catch (JSchException e) {
                System.out.println("服务器" + baozunurl + "使用用户名:" + username + "无法连接");
                System.out.println("服务器" + testurl + "使用用户名:" + username + "无法连接");
                e.printStackTrace();
            }
            index++;


        }
    }

    @SuppressWarnings("unchecked")
    public void copyFile(ChannelSftp sftpFrom, ChannelSftp sftpTo, String directory, String toDirectory) {
        try {
            Vector<LsEntry> lsEntryVector = sftpFrom.ls(directory);
            for (LsEntry lsEntry : lsEntryVector) {
                String fileName = lsEntry.getFilename();
                if (!StringUtils.startsWith(fileName, ".")) {// 非隐藏文件
                    // 判断在目标目录中是否存在，如果不存在，则新增
                    String childDirectory = directory + "/" + fileName;
                    String childToDirectory = toDirectory + "/" + fileName;
                    try {
                        // 如果该文件中还存在文件夹
                        SftpATTRS sftpATTRS = sftpFrom.lstat(childDirectory);
                        if (sftpATTRS.isDir()) {
                            // 是文件夹才行
                            if (!isDirExist(sftpTo, childToDirectory)) {
                                System.out.println("开始执行拷贝" + childDirectory);
                                sftpTo.mkdir(childToDirectory);
                            }
                            copyFile(sftpFrom, sftpTo, childDirectory, childToDirectory);
                        }
                    } catch (SftpException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        break;
                    }
                }
            }
        } catch (SftpException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }

    public ChannelSftp getSftp(Session sshSession, ChannelSftp sftp, String host, int port, String username, String password) throws JSchException {
        JSch jsch = new JSch();
        sshSession = jsch.getSession(username, host, port);
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        return sftp;
    }

    public boolean isDirExist(ChannelSftp chnSftp, String directory) throws SftpException {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = chnSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }
}
